<?php $emacs=0;

/**
 * A map coordinate that can convert into a decimal version.
 */
class Coord {

  function Coord($degrees,$minutes,$seconds) {
    $this->degrees = $degrees;
    $this->minutes = $minutes;
    $this->seconds = $seconds;
  }

  function getDegrees() {
    return $this->degrees;
  }
  
  function getMinutes() {
    return $this->minutes;
  }
  
  function getSeconds() {
    return $this->seconds;
  }
  
  function toDecimal() {
    return $this->degrees + $this->minutes/60 + $this->seconds/3600;
  }
  
}

/**
 * Geo information that can be initialized from an image using the
 * EXIF data.  It's essentially a pair of coords:
 *  - getLatCoord()
 *  - getLngCoord()
 * and their decimal versions
 *  - getLat()
 *  - getLng()
 *
 * NOTE: This currently works for Iphone images.
 */
class GeoInformation {
  function GeoInformation($image) {
    if (!is_file($image)) return;
    $arr = exif_read_data($image);
    $lat_arr = $arr['GPSLatitude'];
    $lng_arr = $arr['GPSLongitude'];
    $lat_ref = $arr['GPSLatitudeRef'];
    $lng_ref = $arr['GPSLongitudeRef'];
    $this->lat = $this->createCoord($lat_arr,$lat_ref);
    $this->lng = $this->createCoord($lng_arr,$lng_ref);
  }

  function getLat() {
    return $this->lat ? $this->lat->toDecimal() : NULL;
  }

  function getLng() {
    return $this->lng ? $this->lng->toDecimal() : NULL;
  }

  function getLatCoord() {
    return $this->lat;
  }

  function getLngCoord() {
    return $this->lng;
  }

  function isValid() {
    return $this->lat && $this->lng;
  }

  function createCoord($arr,$ref) {
    if (!$arr) return NULL;
    if (count($arr) != 3) return NULL;
    $value = array();
    for ($i=0; $i<3; $i++) {
      $value[$i] = preg_split('/\//',$arr[$i]);
    }
    $degrees = $value[0][0]/$value[0][1];
    $minutes = $value[1][0]/$value[1][1];
    $seconds = $value[2][0]/$value[2][1];

    if ($ref == 'S' || $ref == 'W') $degrees *= -1;
    return new Coord($degrees,$minutes,$seconds);
  } 

  function toString() {
    return '(' . $this->getLat() . ',' . $this->getLng() . ')';
  }
}

/**
 * @param name the id of the image, e.g. 123098123098123098
 * @return <code>TRUE</code> if this name has a geo location.
 */
function hasGeoInformation($name) {
  $geo = new GeoInformation(fullImageName($name));
  return $geo->isValid();
}

?>